package com.cskaoyan.login;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.*;

/**
 * 创建日期: 2022/06/30 14:22
 *
 * @author ciggar
 *
 * 登录案例
 *
 * 解释数据库的注入问题
 */
public class LoginDemo {

    public static void mainForStatement(String[] args) throws SQLException {

//        boolean ret = login("长风", "xxx");
        boolean ret = login("长风", "asddasefwe' or  '1");
        // select * from t_user where username = '长风'  and password ='xxx'
        // select * from t_user where username = '长风'  and password ='eafwefw' or  '1';

        if (ret) {

            System.out.println("登录成功!");
        }else {
            System.out.println("登录失败！");
        }


    }

    public static void main(String[] args) throws SQLException {


//        boolean ret = loginUsePreparedStatement("长风", "asddasefwe' or  '1");

        boolean ret = loginUsePreparedStatement("长风", "bmw");

        if (ret) {

            System.out.println("登录成功!");
        }else {
            System.out.println("登录失败！");
        }


    }







    // 登录的方法
    public static boolean login(String username,String password) throws SQLException {

        // 获取连接对象
        Connection connection = JDBCUtils.getConnection();

        // 获取statement对象
        Statement statement = connection.createStatement();

        String sql = "select * from t_user where username = '"+username+"'  and password ='"+password+"'";

        System.out.println("sql:" + sql);

        // 通过SQL语句查询数据库
        ResultSet resultSet = statement.executeQuery(sql);

        if (resultSet.next()) {
            return true;
        }
        return false;
    }



    // 登录的方法，使用PreparedStatement
    public static boolean loginUsePreparedStatement(String username,String password) throws SQLException {

        // 获取连接对象
        Connection connection = JDBCUtils.getConnection();

        // 获取PreparedStatement
        // 1. 需要传入一个SQL语句，这个SQL语句中的参数值可以不写，用问号来占位
        // 2. 在创建PreparedStatement的时候，客户端会把这个SQL语句发送给MySQL服务器进行编译解析
        // 3. 后续传入的参数，即使是关键字，也不会再次解析了，只会被当成普通的字符串去赋值
        PreparedStatement preparedStatement = connection.prepareStatement("select * from t_user where username = ? and password = ?");


        // 赋值
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);


        // 执行SQL语句，获取结果
        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
            return true;
        }else {
            return false;
        }


    }
}
